package com.unlcn.ils.wms.web.controller.baseData;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.unlcn.ils.wms.backend.bo.baseDataBO.CustomerNameList;
import com.unlcn.ils.wms.backend.bo.baseDataBO.VehicleSpecBO;
import com.unlcn.ils.wms.backend.service.inbound.*;
import com.unlcn.ils.wms.base.businessDTO.baseData.WmsEmptyLocationDTO;
import com.unlcn.ils.wms.base.model.inbound.WmsWarehouseNoticeDetail;
import com.unlcn.ils.wms.base.model.inbound.WmsWarehouseNoticeHead;
import com.unlcn.ils.wms.base.model.stock.WmsLocation;
import com.unlcn.ils.wms.base.model.stock.WmsZone;
import com.unlcn.ils.wms.web.utils.HttpClientUtils;
import com.unlcn.ils.wms.web.utils.Vo2Bo;
import com.unlcn.ils.wms.web.vo.baseData.WmsEmptyZoneVO;
import com.unlcn.ils.wms.web.vo.inbound.AreaTreeVO;
import com.unlcn.ils.wms.web.vo.inbound.Nodes;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 基础数据
 * Created by DELL on 2017/8/15.
 */
@Controller
@RequestMapping("/baseData")
@ResponseBody
public class WmsBaseDataController {

    private Logger logger = LoggerFactory.getLogger(WmsBaseDataController.class);

    private static String REST_ROOT_URL = "http://218.76.52.119/ils";
    @Autowired
    WmsZoneLocationService wmsZoneLocationService;
    @Autowired
    WmsStrategyService wmsStrategyService;
    @Autowired
    WmsInboundPloyService wmsInboundPloyService;
    @Autowired
    private AsnOrderService asnOrderService;
    @Autowired
    private WmsInboundAsnService wmsInboundAsnService;

    @Value("${sc.getScUrl.url}")
    private String getScUrl;

    /**
     * 获得当前仓库的所有库区
     * todo 仓库是从session取，还是直接由前端传需要待确定
     *
     * @param whCode
     * @return
     */
    @RequestMapping(value = "/getZone/{whCode}")
    public ResultDTO getZone(@PathVariable("whCode") String whCode) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<WmsZone> wmsZoneList = wmsZoneLocationService.getZone(whCode);
            resultDTO.setSuccess(true);
            resultDTO.setData(wmsZoneList);
            resultDTO.setMessage("查询成功");
            resultDTO.setMessageCode("200");
            return resultDTO;
        } catch (BusinessException ex) {
            logger.error("WmsBaseDataController.getZone error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询异常");
            resultDTO.setMessageCode("500");
            return resultDTO;
        }
    }

    /**
     * 获得当前仓库的所有空库区
     *
     * @param whCode
     * @return
     */
    @RequestMapping("/getEmptyZone/{whCode}")
    public ResultDTO getEmptyZone(@PathVariable("whCode") String whCode) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<WmsEmptyLocationDTO> wmsEmptyZoneStrList = wmsZoneLocationService.getEmptyZone(whCode);
            Vo2Bo<WmsEmptyZoneVO, WmsEmptyLocationDTO> converter = new Vo2Bo();
            List<WmsEmptyZoneVO> wmsZoneVOList = converter.convert(wmsEmptyZoneStrList, WmsEmptyZoneVO.class);
            List<WmsEmptyZoneVO> wmsEmptyZoneList = Lists.newArrayList();
            wmsZoneVOList.stream().forEach(
                    v -> {
                        if (!wmsEmptyZoneList.contains(v)) {
                            wmsEmptyZoneList.add(v);
                        }
                    }
            );
            resultDTO.setSuccess(true);
            resultDTO.setData(wmsEmptyZoneList);
            resultDTO.setMessage("查询成功");
            resultDTO.setMessageCode("200");
            return resultDTO;
        } catch (BusinessException ex) {
            logger.error("WmsBaseDataController.getEmptyZone error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询异常");
            resultDTO.setMessageCode("500");
            return resultDTO;
        }

    }

    /**
     * 获得当前仓库的所有库位
     * todo 仓库是从session取，还是直接由前端传需要待确定
     *
     * @param whCode
     * @return
     */
    @RequestMapping(value = "/getLocation/{whCode}")
    public ResultDTO getLocation(@PathVariable("whCode") String whCode) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<WmsLocation> wmsLocation = wmsZoneLocationService.getLocation(whCode);
            resultDTO.setData(wmsLocation);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("查询成功");
            resultDTO.setMessageCode("200");
            return resultDTO;
        } catch (BusinessException ex) {
            logger.error("WmsBaseDataController.getLocation error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询异常");
            resultDTO.setMessageCode("500");
            return resultDTO;
        }
    }

    /**
     * 获得当前仓库的所有空库位
     *
     * @param whCode
     * @return
     */
    @RequestMapping("/getEmptyLocation/{whCode}/{zoneId}")
    public ResultDTO getEmptyLocation(@PathVariable("whCode") String whCode,
                                      @PathVariable("zoneId") String zoneId) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<WmsEmptyLocationDTO> wmsEmptyLocation = wmsZoneLocationService.getEmptyLocation(whCode, zoneId);
            resultDTO.setSuccess(true);
            resultDTO.setMessageCode("200");
            resultDTO.setMessage("查询成功");
            resultDTO.setData(wmsEmptyLocation);
            return resultDTO;
        } catch (BusinessException ex) {
            logger.error("WmsBaseDataController.getEmptyLocation error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessageCode("500");
            resultDTO.setMessage("查询异常");
            return resultDTO;
        }
    }

    /**
     * 根据仓库类型查询库区
     *
     * @param whCode 仓库code
     * @param whType 类型 合格品区 不良品区
     * @return
     */
    @RequestMapping("/queryQualifiedZone/{whCode}/{whType}")
    public ResultDTO queryQualifiedZone(@PathVariable("whCode") String whCode,
                                        @PathVariable("whType") String whType) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<WmsEmptyLocationDTO> wmsEmptyLocationDTOList = wmsZoneLocationService.queryQualifiedZone(whCode, whType);
            resultDTO.setData("");
            resultDTO.setSuccess(true);
            resultDTO.setMessageCode("200");
            resultDTO.setMessage("查询成功");
        } catch (Exception ex) {
            resultDTO.setSuccess(false);
            resultDTO.setMessageCode("500");
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    ///**
    // * 获取货主客户
    // * @return
    // */
    //@RequestMapping(value="getCustomerInfo")
    //public ResultDTO getCustomerInfo(){
    //    ResultDTO resultDTO = new ResultDTO();
    //    try {
    //        RestTemplate restTemplate = new RestTemplate();
    //        // sso统一认证需要校验登录凭证，模拟httpClient请求时需要在header头设置token信息
    //        HttpHeaders headers = new HttpHeaders();
    //        // 组装apiKey
    //        String accessToken = "Bearer " + "c50dccdf44219207467ea1c02b8510c5";// token为每个应用的apiKey值，需要在sso中申请
    //        headers.set("Authorization", accessToken);
    //        headers.setContentType(MediaType.APPLICATION_JSON);
    //        Consigner consigner = new Consigner();//不传入值 查询全部
    //        //dealer.setId("10");
    //        //组装货主参数
    //        HttpEntity<Consigner> entity = new HttpEntity<>(consigner, headers);
    //        String path = REST_ROOT_URL + "/crmInformation/getConsignorByCon";// 需要配置对应的ip和port
    //        //设置输出list集合对象
    //        ParameterizedTypeReference<List<Consigner>> typeRef = new ParameterizedTypeReference<List<Consigner>>() {
    //        };
    //        ResponseEntity<List<Consigner>> result = restTemplate.exchange(path, HttpMethod.POST, entity, typeRef);
    //        if (result.getStatusCode() == HttpStatus.OK && result.getBody() != null) {
    //            List<Consigner> consignerlist = result.getBody();
    //            /*System.out.println("===" + consignerlist.get(0).getName());
    //            System.out.println("============" + consignerlist);
    //            for (Consigner consigners : consignerlist) {
    //                System.out.println("==============" + consigners);
    //            }*/
    //            resultDTO.setSuccess(true);
    //            resultDTO.setData(consignerlist);
    //        }else{
    //            resultDTO.setSuccess(false);
    //            resultDTO.setMessage("获取客户信息异常");
    //        }
    //    }catch(Exception ex){
    //        resultDTO.setSuccess(false);
    //        resultDTO.setMessage("获取客户信息异常");
    //        logger.error("baseData.getCustomerInfo=======获取客户信息异常"+ex.getStackTrace());
    //    }
    //    return resultDTO;
    //}


    /**
     * 获取货主客户
     * <p>
     * 2018-4-23 入库通知单重构，此方法 新方法
     * </p>
     */
    @RequestMapping(value = "/getCustomerInfo", method = RequestMethod.GET)
    public ResultDTO<List<WmsWarehouseNoticeHead>> getCustomerInfo(HttpServletRequest request) {
        logger.info("WmsBaseDataController.getCustomerInfo");
        ResultDTO<List<WmsWarehouseNoticeHead>> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            String whCode = request.getHeader("whCode");
            List<WmsWarehouseNoticeHead> customerNameList = wmsInboundAsnService.getAllCustomerName(whCode);
            resultDTO.setData(customerNameList);
        } catch (BusinessException be) {
            logger.error("WmsBaseDataController.getCustomerInfo businessException:", be);
            resultDTO.setData(null);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(be.getMessage());
        } catch (Exception e) {
            logger.error("WmsBaseDataController.getCustomerInfo error:", e);
            resultDTO.setData(null);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }


    /**
     * 获取货主客户
     * <p>
     * 2018-4-23 入库通知单重构，此方法过时 新方法{@link WmsBaseDataController#getCustomerInfo}
     * </p>
     */
    @RequestMapping(value = "/getCustomerInfo-old", method = RequestMethod.GET)
    @Deprecated
    public ResultDTO<List<CustomerNameList>> getCustomerInfoOld(HttpServletRequest request) {
        logger.info("WmsBaseDataController.getCustomerInfoOld");
        ResultDTO<List<CustomerNameList>> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            List<CustomerNameList> allCustomerName = wmsInboundAsnService.getAllCustomerNameOld(whCode);
            resultDTO.setData(allCustomerName);
        } catch (Exception e) {
            resultDTO.setData(null);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return resultDTO;
    }

    /**
     * 从入库订单表获得车型数据
     * <p>
     * 2018-4-23 入库通知单重构 此为新方法
     * </p>
     */
    @RequestMapping(value = "/getVehicleSpec", method = RequestMethod.GET)
    public ResultDTO<List<WmsWarehouseNoticeDetail>> getVehicleSpec(HttpServletRequest request) {
        ResultDTO<List<WmsWarehouseNoticeDetail>> resultDTO = new ResultDTO<>();
        try {
            String whCode = request.getHeader("whCode");
            List<WmsWarehouseNoticeDetail> data = asnOrderService.getVehicleSpec(whCode);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("获取车型数据成功");
            resultDTO.setData(data);
        } catch (BusinessException be) {
            logger.error("WmsBaseDataController.getVehicleSpec businessException:", be);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(be.getMessage());
        } catch (Exception ex) {
            logger.error("WmsBaseDataController.getVehicleSpec error:", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取车型数据异常");
        }
        return resultDTO;
    }


    /**
     * 从入库订单表获得车型数据
     * <p>
     * 2018-4-23 入库通知单重构 此方法过时{@link WmsBaseDataController#getVehicleSpec}
     * </p>
     */
    @RequestMapping(value = "/getVehicleSpec-old", method = RequestMethod.GET)
    @Deprecated
    public ResultDTO getVehicleSpecOld(HttpServletRequest request) {
        ResultDTO<List<VehicleSpecBO>> resultDTO = new ResultDTO<>();
        try {
            //String url = getScUrl + "api/brandSeries/getModels?pageSize=20";
            //String url = "http://120.77.8.167/sc-api/api/brandSeries/getModels?pageSize=20";//+Integer.MAX_VALUE;//uat
            /*PageVo pageVo = new PageVo();
            pageVo.setPageNo(1);
            pageVo.setPageSize(20);
            String param = "?pageNo="+pageVo.getPageNo()+"&pageSize="+pageVo.getPageSize();
            String url = "http://10.20.30.111/ils-sc-api/api/brandSeries/getModels"+param;
            String str = HttpClientUtils.getJson(url);
            Map map = new ObjectMapper().readValue(str, Map.class);
            List<Map> data = (List)map.get("data");//去掉其他参数，只需要用到data数据*/
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            List<VehicleSpecBO> vehicleSpecBOList = asnOrderService.getVehicleSpecOld(whCode);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("获取车型数据成功");
            resultDTO.setData(vehicleSpecBOList);
            return resultDTO;
        } catch (Exception ex) {
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取车型数据异常");
            logger.error("WmsBaseDataController.getVehicleSpecOld error  获取车型数据异常" + ex.getStackTrace());
            return resultDTO;
        }
    }

    @RequestMapping(value = "/getAreaTree/{parentId}")
    public ResultDTO getAreaTree(@PathVariable String parentId) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            String url = getScUrl + "api/area/getAllArea/" + parentId;
            String str = HttpClientUtils.getJson(url);
            Map map = new ObjectMapper().readValue(str, Map.class);
            List<Map> data = (List) map.get("data");//去掉其他参数，只需要用到data数据
            resultDTO.setData(data);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("查询区域成功");
            return resultDTO;
        } catch (Exception ex) {
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询区域异常");
            return resultDTO;
        }

    }

    @RequestMapping(value = "getArea")
    public ResultDTO getArea() {
        ResultDTO resultDTO = new ResultDTO();
        try {
            String url = getScUrl + "api/area/getAllCity?pageSize=" + Integer.MAX_VALUE;//dev
            String str = HttpClientUtils.getJson(url);
            Map map = new ObjectMapper().readValue(str, Map.class);
            List<Map> data = (List) map.get("data");//去掉其他参数，只需要用到data数据
            List<AreaTreeVO> areaTreeVOList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(data)) {
                data.stream().forEach(v -> {
                    AreaTreeVO areaTreeVO = new AreaTreeVO();
                    areaTreeVO.setId(Long.valueOf(v.get("id").toString()));
                    areaTreeVO.setParentId(Long.valueOf(v.get("parentId").toString()));
                    areaTreeVO.setCode(v.get("code").toString());
                    areaTreeVO.setName(v.get("name").toString());
                    areaTreeVO.setSname(v.get("sname").toString());
                    areaTreeVOList.add(areaTreeVO);
                });
            }


            List<Nodes> nodes = getAreaData(areaTreeVOList);
            ObjectMapper mapper = new ObjectMapper();
            //String ztreeNodes = mapper.writeValueAsString(nodes);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("获取区域数据成功");
            resultDTO.setData(nodes);
            return resultDTO;
        } catch (Exception ex) {
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取区域数据异常");
            logger.error("WmsBaseDataController.getVehicleSpecOld error  获取区域数据异常" + ex.getStackTrace());
            return resultDTO;
        }
    }

    private List<Nodes> getAreaData(List<AreaTreeVO> areaList) {
        List<Nodes> list = Lists.newArrayList();
        for (AreaTreeVO areaTreeVO : areaList) {
            Nodes node = new Nodes();
            node.setId(areaTreeVO.getId() != null ? areaTreeVO.getId().toString() : "");
            node.setpId(areaTreeVO.getParentId() != null ? areaTreeVO.getParentId().toString() : "");
            if (areaTreeVO.getParentId() != null && areaTreeVO.getParentId().equals(0)) {
                node.setName("中国");
            } else {
                node.setName(areaTreeVO.getName());
            }
            node.setOpen(true);
            /*if(wmsInboundPloyFlowtoList != null && wmsInboundPloyFlowtoList.size() > 0) {
                for(WmsInboundPloyFlowto wmsInboundPloyFlowto : wmsInboundPloyFlowtoList){
                    originCode.add(wmsInboundPloyFlowto.getPyfFromCode());
                    destCode.add(wmsInboundPloyFlowto.getPyfToCode());
                }
                if("origin".equals(type) && !originCode.contains(areaTreeVO.getCode())) {
                    node.setNocheck(true);
                }if("dest".equals(type) && !destCode.contains(areaTreeVO.getCode())){
                    node.setNocheck(true);
                }
            }else{
                node.setNocheck(false);
            }*/
            list.add(node);
        }
        return list;
    }

    /**
     * 获取颜色下拉
     * <p>
     * 2018-4-23 因入库通知单重构,重写此方法
     * </p>
     */
    @RequestMapping(value = "/getColorList", method = RequestMethod.GET)
    public ResultDTO<Object> getColorList(HttpServletRequest request) {
        logger.info("WmsBaseDataController.getColorList");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取颜色下拉数据成功");
        try {
            String whCode = request.getHeader("whCode");
            resultDTO.setData(asnOrderService.getColorList(whCode));
        } catch (BusinessException be) {
            logger.error("WmsBaseDataController.getColorList BusinessException: {}", be);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(be.getMessage());
        }catch (Exception e) {
            logger.error("WmsBaseDataController.getColorList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取颜色下拉数据失败");
        }
        return resultDTO;
    }

    /**
     * 获取颜色下拉
     * <p>
     * 2018-4-23 因入库通知单重构,此方法过时新方法{@link WmsBaseDataController#getColorList}
     * </p>
     */
    @RequestMapping(value = "/getColorList-old", method = RequestMethod.GET)
    @Deprecated
    public ResultDTO<Object> getColorListOld(HttpServletRequest request) {
        logger.info("WmsBaseDataController.getColorListOld");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取颜色下拉数据成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            resultDTO.setData(asnOrderService.getColorListOld(whCode));
        } catch (Exception e) {
            logger.error("WmsBaseDataController.getColorListOld error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取颜色下拉数据失败");
        }
        return resultDTO;
    }
}